<template>
  <div class="app-container home" ref="home">
    <div class="main px-xl-5 px-lg-4 px-3">
      <div class="chat-body">
        <!-- Chat Box Header -->
        <!-- end Chat Box Header -->

        <div class="chat-content" id="scrollRef" ref="scrollRef">
          <!-- <v-md-preview :text="receive"
                        ref="receive" /> -->

          <div class="container-xxl">
            <ul
              class="list-unstyled py-4"
              v-for="(item, index) of messageList"
              :key="index"
            >
              <!-- Right Message -->
              <li class="d-flex message right">
                <div class="message-body">
                  <span class="date-time text-muted"></span>
                  <div
                    class="message-row align-items-center justify-content-end"
                  >
                    <div class="message-send-title message-content p-3">
                      <div class="message-user-icon">
                        <img :src="avatar" class="userprofile" />
                      </div>
                      <div class="message-user-ques">{{ item.send }}</div>
                    </div>
                  </div>
                </div>
              </li>
              <!-- end Right Message -->
              <!-- Left Message -->

              <li class="d-flex message" v-if="item.receive">
                <!-- <div class="mr-lg-3 me-2">
                  <img class="avatar sm rounded-circle"
                       src="../assets/chatgpt.jpg"
                       alt="avatar" />
                </div> -->
                <div class="message-body">
                  <div class="message-row d-flex align-items-center">
                    <div class="message-reply message-content p-3">
                      <div class="message-user-icon">
                        <div class="message-reply-icon">
                          <img :src="headImg" class="reply-icon" />

                          <!-- <svg
                            t="1733890609735"
                            class="reply-icon"
                            viewBox="0 0 1024 1024"
                            version="1.1"
                            xmlns="http://www.w3.org/2000/svg"
                            p-id="5910"
                            width="200"
                            height="200"
                          >
                            <path
                              d="M576 85.333333c0 18.944-8.234667 35.968-21.333333 47.701334V213.333333h213.333333a128 128 0 0 1 128 128v426.666667a128 128 0 0 1-128 128H256a128 128 0 0 1-128-128V341.333333a128 128 0 0 1 128-128h213.333333V133.034667A64 64 0 1 1 576 85.333333zM256 298.666667a42.666667 42.666667 0 0 0-42.666667 42.666666v426.666667a42.666667 42.666667 0 0 0 42.666667 42.666667h512a42.666667 42.666667 0 0 0 42.666667-42.666667V341.333333a42.666667 42.666667 0 0 0-42.666667-42.666666H256z m-170.666667 128H0v256h85.333333v-256z m853.333334 0h85.333333v256h-85.333333v-256zM384 618.666667a64 64 0 1 0 0-128 64 64 0 0 0 0 128z m256 0a64 64 0 1 0 0-128 64 64 0 0 0 0 128z"
                              fill="#fff"
                              p-id="5911"
                            ></path>
                          </svg> -->
                        </div>
                      </div>
                      <div class="message-reply-cont">
                        <v-md-preview
                          :text="item.receive"
                          @click.native="
                            relationQuestionClick($event, '传递的实参')
                          "
                        />
                      </div>
                    </div>
                  </div>
                </div>
              </li>
              <!-- end Left Message -->
              <!-- Loading Message -->
              <li class="d-flex message" v-if="item.loading">
                <!-- <div class="mr-lg-3 me-2">
                  <img class="avatar sm rounded-circle"
                       src="../assets/chatgpt.jpg"
                       alt="avatar" />
                </div> -->
                <div class="message-body">
                  <div class="message-row d-flex align-items-center">
                    <div class="message-content p-3">
                      <div class="wave">
                        <span class="dot"></span>
                        <span class="dot"></span>
                        <span class="dot"></span>
                      </div>
                    </div>
                  </div>
                </div>
              </li>
              <!-- end Loading Message -->
            </ul>
          </div>
        </div>
      </div>
    </div>
    <div
      class="chat-footer border-top py-xl-4 py-lg-2 py-2"
      :style="{ width: computedWidth + 'px' }"
    >
      <div class="chat-footer-in">
        <div class="row">
          <div class="col-12">
            <ul class="attachment-file" v-if="attachmentFile.length">
              <li
                v-for="(item, key) in attachmentFile"
                :key="key"
                class="attachment-file-item"
              >
                <div class="btn-close-svg" @click="deleteAttachmentFile(key)">
                  <svg
                    viewBox="0 0 24 24"
                    xmlns="http://www.w3.org/2000/svg"
                    width="24"
                    height="24"
                    fill="currentColor"
                  >
                    <path
                      d="M11.9997 10.5865L16.9495 5.63672L18.3637 7.05093L13.4139 12.0007L18.3637 16.9504L16.9495 18.3646L11.9997 13.4149L7.04996 18.3646L5.63574 16.9504L10.5855 12.0007L5.63574 7.05093L7.04996 5.63672L11.9997 10.5865Z"
                    ></path>
                  </svg>
                </div>
                <div class="attachment-name">
                  <svg-icon :icon-class="item.extension" />{{ item.name }}
                </div>
                <div class="attachment-detail">
                  <div>{{ item.size }}</div>
                </div>
              </li>
            </ul>
            <div class="input-group align-items-center">
              <input
                type="text"
                v-model="prompt"
                class="form-control border-0 pl-0"
                placeholder="Type your message..."
              />
              <div class="input-group-append">
                <span class="input-group-text border-0 pr-0">
                  <button
                    type="submit"
                    :class="[
                      'btn',
                      buttonDisabled
                        ? 'btn-submit-disable'
                        : 'btn-submit-active',
                    ]"
                    :disabled="buttonDisabled"
                    @click="handleSubmit"
                  >
                    <i class="el-icon-top"></i>
                  </button>
                </span>
              </div>
            </div>
          </div>
        </div>
        <div class="chat-focus-list">
          <div class="chat-focus" @click="showpop('focus')">
            <span class="el-icon-setting"></span>焦点
          </div>
          <div class="chat-focus" @click="showpop('attachment')">
            <span class="el-icon-circle-plus-outline"></span>附加
          </div>
        </div>
        <ul class="attachmentlist" v-if="isfocus">
          <div class="btn-close-svg" @click="closepop('focus')">
            <svg
              viewBox="0 0 24 24"
              xmlns="http://www.w3.org/2000/svg"
              width="24"
              height="24"
              fill="currentColor"
            >
              <path
                d="M11.9997 10.5865L16.9495 5.63672L18.3637 7.05093L13.4139 12.0007L18.3637 16.9504L16.9495 18.3646L11.9997 13.4149L7.04996 18.3646L5.63574 16.9504L10.5855 12.0007L5.63574 7.05093L7.04996 5.63672L11.9997 10.5865Z"
              ></path>
            </svg>
          </div>
          <li
            class="el-icon-box type-icon"
            :class="{ 'type-icon-active': !languagetype }"
            @click="getchange(false)"
          >
            <div class="txt">通用</div>
          </li>
          <li
            class="el-icon-star-off type-icon"
            :class="{ 'type-icon-active': languagetype }"
            @click="getchange(true)"
          >
            <div class="txt">学术</div>
          </li>
        </ul>
        <ul class="attachmentlist" v-if="isAttachment">
          <div class="btn-close-svg" @click="closepop('attachment')">
            <svg
              viewBox="0 0 24 24"
              xmlns="http://www.w3.org/2000/svg"
              width="24"
              height="24"
              fill="currentColor"
            >
              <path
                d="M11.9997 10.5865L16.9495 5.63672L18.3637 7.05093L13.4139 12.0007L18.3637 16.9504L16.9495 18.3646L11.9997 13.4149L7.04996 18.3646L5.63574 16.9504L10.5855 12.0007L5.63574 7.05093L7.04996 5.63672L11.9997 10.5865Z"
              ></path>
            </svg>
          </div>
          <li>
            <el-upload
              class="upload-demo"
              action="#"
              ref="upload"
              :show-file-list="false"
              :file-list="fileList"
              :http-request="handleFileUpload"
            >
              <div class="upload-icon-txt">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">附加</div>
              </div>
            </el-upload>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { fetchEventSource } from "@microsoft/fetch-event-source";
import { conversations, messages, upload } from "@/api/ai";
import { addchattopic, addchatdetail } from "@/api/chat";
import { v4 } from "uuid";
import qs from "qs";
import { mapGetters, mapActions } from "vuex";
import { scrollTo } from "@/utils/scroll-to";
import { formatBytes, deepClone } from "@/utils";
export default {
  name: "Index",
  data() {
    return {
      // 版本号
      isAttachment: false,
      attachmentFile: [],
      fileList: [],
      languagetype: false,
      fileName: "",
      fileSize: 0,
      version: "3.8.2",
      prompt: "",
      buttonDisabled: false,
      fileUploadCard: false,
      messageList: [],
      fileContent: "",
      formattedFileSize: "0B",
      conversationList: [],
      titlecontent: "",
      receive: "",
      abort: "",
      eventSource: null,
      object: {},
      windowsclientWidth: "",
      headImg: require("@/assets/logo.png"),
      isfocus: false,
      questionLineNum: 8,
    };
  },
  watch: {},
  computed: {
    ...mapGetters([
      "name",
      "sidebar",
      "device",
      "avatar",
      "chatList",
      "currentTopicId",
      "chatfromdify",
    ]),
    computedWidth() {
      let _winwidth =
        this.windowsclientWidth -
        (this.device === "mobile" ? 0 : this.sidebar.opened ? 200 : 54) -
        40;
      return _winwidth;
    },
  },
  beforeMount() {
    // this.chattopic();
    window.addEventListener("resize", this._computedWidth);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this._computedWidth);
  },
  mounted() {
    this.questionLineNum = Math.floor(
      (this.$refs.home.offsetWidth - 130) / 160
    );
    this.initResize();
    window.addEventListener("resize", this.resizeFunction, false);

    this.$bus.$on("changeCurrentTopic", (topic_id) => {
      this.buttonDisabled = false;
      this.changeTocurrentTopic(topic_id, !this.chatfromdify);
    });
    let id = this.$route.query.id;
    if (id) {
      this.changeTocurrentTopic(id, !this.chatfromdify);
    }

    // this.conversations();
    this.windowsclientWidth = document.body.clientWidth;
  },
  beforeDestroy() {
    this.$bus.$off("changeCurrentTopic");
    this.removeResize();
  },
  methods: {
    ...mapActions("chat", ["getchattopic", "setCurrentTopicId"]),
    closepop(name) {
      if (name === "focus") {
        this.isfocus = false;
      } else if (name === "attachment") {
        this.isAttachment = false;
      }
    },
    initResize() {
      window.addEventListener("resize", this.resizeFunction, false);
    },
    removeResize() {
      window.removeEventListener("resize", this.resizeFunction);
    },
    resizeFunction() {
      this.questionLineNum = Math.floor(
        (this.$refs.home.offsetWidth - 130) / 160
      );
    },
    deleteAttachmentFile(key) {
      let attachmentFile = this.attachmentFile;
      let res = attachmentFile.filter((item, itemkey) => itemkey !== key);
      this.attachmentFile = res;
    },
    showAttachment() {
      this.isfocus = false;
      this.isAttachment = true;
    },
    handleFileUpload(file) {
      this.loading = true;
      const formData = new FormData();
      formData.append("file", file.file);
      formData.append("user", this.name);
      // 调用后端服务器的接口
      upload(formData)
        .then((resp) => {
          this.attachmentFile = [
            ...this.attachmentFile,
            {
              name: resp.name,
              size: formatBytes(resp.size),
              extension: resp.extension,
              id: resp.id,
            },
          ];
          this.isAttachment = false;
        })
        .catch((e) => {
          this.$message.error(e.message);
          this.$refs.upload.clearFiles();
        });
    },

    showpop(name) {
      if (name === "focus") {
        this.isfocus = true;
        this.isAttachment = false;
      } else if (name === "attachment") {
        this.isfocus = false;
        this.isAttachment = true;
      }
    },
    async conversations() {
      let data = {
        user: this.name,
        limit: 100,
      };
      let str = qs.stringify(data);
      await conversations(data);
    },
    // async chattopic() {
    //   let res = await chattopic();
    // },
    getchange(languagetype) {
      this.languagetype = languagetype;
      this.isfocus = false;
      console.log(languagetype, "#####");
    },
    relationQuestionClick(event, arg) {
      console.log(event.target.className, "?????????");
      if (/question-arrow/.test(event.target.className)) {
        let question = event.target.previousElementSibling.innerHTML;
        this.onConversation(question);
      } else if (/morerelation/.test(event.target.className)) {
        let childNodes = event.target.previousElementSibling.children;
        if (event.target.innerHTML === "更多") {
          for (let i = 0; i < childNodes.length; i++) {
            childNodes[i].className = "linkbox";
          }
          event.target.innerHTML = "收起";
        } else {
          for (let i = 0; i < childNodes.length; i++) {
            childNodes[i].className =
              i > this.questionLineNum ? "linkbox hidelinkbox" : "linkbox";
          }
          event.target.innerHTML = "更多";
        }
      }

      // event传不传都有
    },
    _computedWidth() {
      this.windowsclientWidth = document.body.clientWidth;
    },
    handleMouseEnter(e) {
      console.log(e.target, e, "????????????");
      console.log(
        e.target.getElementsByTagName("span")[0].classList.add("dotTextshow"),
        "???????"
      );
    },

    scrollToBottom() {
      this.$nextTick(() => {
        scrollTo(document.documentElement.scrollHeight, 800, null);
        // scrollTo(this.$refs.home.scrollHeight, 800, null, this.$refs.home);
      });
    },
    handleSubmit() {
      // let totalJson = {"urls": ["[1]: https://nph.onlinelibrary.wiley.com/doi/abs/10.1111/nph.12157", "[2]: https://opentextbc.ca/plantidentification/chapter/plant-morphology-flowers-and-fruit/", "[3]: https://www.sciencedirect.com/science/article/abs/pii/S0889157509000192", "[4]: https://www.sciencedirect.com/science/article/abs/pii/S1146609X22000285", "[5]: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7473347/", "[6]: https://www.kloranebotanical.foundation/en/botany/botany-lessons/reference-sheet-fruits", "[7]: https://www.horticultureguruji.in/horticultural-and-botanical-classifications-of-fruits/", "[8]: https://en.wikipedia.org/wiki/Fruit", "[9]: https://www.sciencedirect.com/science/article/abs/pii/S089990071500180X", "[10]: https://thetroutbeckschool.com/the-botanical-classification-of-fruit/"], "titles": ["How colorful are fruits? Limited color diversity in fleshy fruits ...", "16. Plant Morphology – Flowers and Fruit", "Classification of fruits and vegetables - ScienceDirect", "Ecology of morphological fruit types, and fruit and seed ...", "Relationship between color and antioxidant capacity of fruits and ...", "Reference sheet: fruits | Klorane Botanical Foundation", "Horticultural and Botanical Classifications of Fruits - Horticulture ...", "Fruit - Wikipedia", "Classification of fruits based on anthocyanin types and relevance ...", "The botanical classification of fruit | The Troutbeck School"]}
      // console.log(totalJson["urls"])

      // console.log(s);
      // this.receive = s;

      this.onConversation();
    },
    processData(text, type) {
      let _this = this;
      if (text && text.replace(/\s/g, "") === "[END]") {
        _this.messageList[_this.messageList.length - 1].loading = false;
        _this.buttonDisabled = false;
        _this.eventSource = null;
        _this.saveChatDetail();
        _this.abort.abort();
        _this.getchattopic();
        _this.scrollToBottom();
        console.log(_this.titlecontent, "??????????????????")
      } else if (
        (/(?=.*workflow_started)^.*$/.test(text) ||
          /(?=.*{"event":\s*"message")^.*$/.test(text)) &&
        /conversation_id/.test(text)
      ) {
        let conversation_info = JSON.parse(text);
        if (!this.currentTopicId) {
          this.setCurrentTopicId(conversation_info["conversation_id"]);
        }
      } else {
        var chunkData = text;
        if (/(?=.*urls)(?=.*titles)^.*$/.test(chunkData)) {
          let titledata = JSON.parse(chunkData);
          let urls = titledata["urls"];
          let titles = titledata["titles"];
          let titlecontent = "";
          _this.object = {};
          if (!(titles.length && urls.length)) {
            return;
          } else {
            let normal_titles = titles.filter(
              (item) => !["", null, undefined, NaN, false, true].includes(item)
            );
            let normal_urls = urls.filter(
              (item) => !["", null, undefined, NaN, false, true].includes(item)
            );
            if (!(normal_titles.length && normal_urls.length)) {
              return;
            }
          }
          titlecontent +=
            "<div class='model-title el-icon-connection'>来源</div>";
          titlecontent += "<div class='linkboxTotal'>";

          let length;
          let isMore;
          let questionLineNum = this.questionLineNum;
          if (titledata["urls"].length > questionLineNum) {
            length = questionLineNum;
            isMore = true;
          } else {
            length = titledata["urls"].length;
            isMore = false;
          }
          for (let i = 0; i < titledata["urls"].length; i++) {
            let titlekey = i;
            titlecontent +=
              "<div class='linkbox" +
              (i >= questionLineNum ? " hidelinkbox" : "") +
              "'>";
            titlecontent +=
              "<div class='linktitle'>" + titles[titlekey] + "</div>";
            let numLink = urls[titlekey].replace(/[\"\']/g, "").split(/\:\s+/);
            titlecontent +=
              "<div class='numlink'>" +
              numLink[0] +
              "<div class='linkurl'>" +
              numLink[1] +
              "</div>" +
              "</div>";
            titlecontent += "</div>";
          }
          titlecontent += "</div>";
          titlecontent += isMore ? "<div class='morerelation'>更多</div>" : "";

          for (let i = 0; i < titledata["urls"].length; i++) {
            let split = titledata["urls"][i].split(/:(?!\/)/);
            if (split.length > 1) {
              let num = split[0].replace(/[\[\]]/g, "");
              if (!_this.object[num]) {
                _this.object[num] = {};
              }
              _this.object[num]["link"] = split[1];
              _this.object[num]["title"] = titledata["titles"][i].replace(
                /\s+/,
                ""
              );
            }
          }

          _this.titlecontent += titlecontent;
        } else if (/(?=.*{"questions":)^.*$/.test(chunkData)) {
          let isChinese = /.*[\u4e00-\u9fa5]+.*$/.test(
            _this.messageList[_this.messageList.length - 1]["send"]
          );
          let questionData = JSON.parse(chunkData);
          let questionsList = questionData["questions"];
          if (questionData && questionsList.length) {
            let titlecontent = "<ul class='related-question'>";
            titlecontent +=
              "<div class='model-title el-icon-paperclip'>相关的</div>";
            for (let i = 0; i < questionsList.length; i++) {
              if (questionsList[i]) {
                titlecontent +=
                  "<li><div class='question-content'>" +
                  questionsList[i] +
                  "</div><div class='question-arrow el-icon-right'></div></li>";
              }
            }
            titlecontent += "</ul>";
            _this.titlecontent += titlecontent;
          }
        } else {
          if (chunkData.replace(/\s+/, "") === "") {
            return;
          }
          if (
            !/<div\s+class='model-title\s+el-icon-chat-dot-square'>答案<\/div>/.test(
              _this.titlecontent
            )
          ) {
            _this.titlecontent +=
              "<div class='model-title el-icon-chat-dot-square'>答案</div>";
          }
          _this.titlecontent += chunkData;
          _this.titlecontent = _this.titlecontent.replace(
            /((\*{2}\s*(\:|\：))\s*)(?!<br\/>)/g,
            "$2<br/>"
          );

   

        }
        if (Object.keys(_this.object).length) {
          _this.titlecontent = _this.titlecontent.replace(
            /(?<!<span\s+class\=dot>)\[(\d+)\](?!<\/span>)/g,
            (match, offset, string) => {
              let num = match.replace(/[\[\]]/g, "");
              let matchDiv;
              if (
                _this.object[num] &&
                _this.object[num]["title"] &&
                _this.object[num]["link"]
              ) {
                matchDiv =
                  "<span>" +
                  _this.object[num]["title"] +
                  "</span><a href=" +
                  _this.object[num]["link"] +
                  " target='_blank'>" +
                  _this.object[num]["link"] +
                  "</a>";
              }
              return matchDiv
                ? "<span class=dotcontainer><span class=dot>" +
                    num +
                    "</span><span class=dotText>" +
                    matchDiv +
                    "</span></span>"
                : match;
            }
          );
        }
        console.log(_this.titlecontent,"????????")
        _this.titlecontent = _this.titlecontent.replace(/(?<!#)(#)(?!#)(\s+)/,"$1$1$2")
        // _this.titlecontent = _this.titlecontent.replace(/#{3}/,"##")
        //  _this.titlecontent = _this.titlecontent.replace(/(?<!#)#{1}(?!#)/g,"##")
        // _this.titlecontent = _this.titlecontent.replace(/[\r\n](#)/g,"$1");
        _this.messageList[_this.messageList.length - 1].receive = 
          _this.titlecontent;
        _this.scrollToBottom();
      }
    },
    async changeTocurrentTopic(id, isLocal) {
      console.log(id, "???????", isLocal);
      let currentChatList;
      this.messageList = [];
      if (id === "") {
        return;
      }
      if (isLocal) {
        currentChatList = this.chatList.filter(
          (item) => item.topic_id === id
        )[0].children;
        if (!(currentChatList && currentChatList.length)) return;
        for (let i = 0; i < currentChatList.length; i++) {
          this.messageList.push({
            send: currentChatList[i]["title"],
            receive: currentChatList[i]["content"],
            loading: false,
          });
        }
      } else {
        let data = { user: this.name, conversation_id: id };
        let res = await messages(data);
        currentChatList = res.data;
        if (!(currentChatList && currentChatList.length)) return;
        for (let i = 0; i < currentChatList.length; i++) {
          this.messageList.push({
            send: currentChatList[i]["query"],
            receive: currentChatList[i]["answer"],
            loading: false,
          });
        }
      }

      console.log(this.messageList, this.$route.path);
      // this.titlecontent +=
    },
    async saveChatDetail() {
      let title = this.messageList[this.messageList.length - 1]["send"];
      let topic_id = this.currentTopicId;
      // console.log(topic_id, ">>>>>>>>>>>>>>>>>");
      if (!topic_id) return;
      await addchatdetail({
        title,
        content: this.titlecontent,
        parent_id: topic_id,
      });
    },
    async onConversation(question) {
      let _this = this;
      let message = question ? question : this.prompt;
      if (!message || message.trim() === "") return;
      if (!this.currentTopicId && !this.chatfromdify) {
        let res = await addchattopic({ topic: message });
        _this.setCurrentTopicId(res.data["topic_id"]);
      }

      // Clear input box and disable button
      this.prompt = "";
      this.buttonDisabled = true;
      this.fileUploadCard = false;
      this.titlecontent = "";

      // Send message (for local display, not directly sent to GPT)
      this.messageList.push({
        send: message,
        receive: "",
        loading: true,
      });
      this.scrollToBottom();

      // Stream request to ChatGPT3.5
      try {
        if (this.fileContent) {
          message += ", Uploaded file content: " + this.fileContent;
        }
        const UUID = v4();
        let data = {
          query: message,
          user: this.name,
          auto_generate: true,
          search_type: this.languagetype ? "science" : "general",
        };
        if (this.currentTopicId) {
          data["conversation_id"] = this.currentTopicId;
        }
        if (this.attachmentFile.length) {
          let file_ids = this.attachmentFile.map((item) => item.id);
          data["file"] = true;
          data["upload_file_ids"] = file_ids.join(",");
        }

        let str = qs.stringify(data);
        this.attachmentFile = [];
        // Send request
        // let response = await fetch("/v1/chat?" + str, {
        //   method: "GET",
        // });

        // let eventSource = new EventSource("/v1/chat?" + str);

        // _this.titlecontent = "";

        // let res = loadFile("./111.txt");
        // _this.messageList[_this.messageList.length - 1].loading = false;
        // let array = res.split("\r\n");
        // for (let i = 0; i < array.length; i++) {
        //   if(array[i]) {

        //      _this.processData(array[i].split("data:")[1]);
        //   }

        // }

        // console.log(array, "########");
        this.abort = new AbortController();
        this.eventSource = fetchEventSource("/v1/chat?" + str, {
          method: "POST",
          openWhenHidden: true,
          headers: {
            "Content-Type": "application/json",
            Accept: "text/event-stream",
            // Authorization: "Bearer app-3KCDfPYou8XURid07rwkSsOY",
          },
          onmessage(event) {
            let lastmessage = _this.messageList[_this.messageList.length - 1];
            if (lastmessage) {
              lastmessage.loading = false;
            }
           let eventdata=  JSON.parse(event.data)
           if(typeof eventdata["answer"] == 'object' ) {
              _this.processData(eventdata["answer"], 'object')
           } else {
              _this.processData(eventdata["answer"], 'string')
           }
           console.log(eventdata["answer"],"####")
          //   _this.processData(eventdata["answer"]);
            // 在这里操作流式数据
          },
          onclose(ee) {
            // 关闭流
          },
          onerror(error) {
            let lastmessage = _this.messageList[_this.messageList.length - 1];
            if (lastmessage) {
              lastmessage.loading = false;
            }

            throw error;
            //返回流报错
          },
        });

        this.fileName = "";
        this.fileSize = 0;
        this.formattedFileSize = "0B";
      } catch (e) {
        console.log(e);
      }
    },

    goTarget(href) {
      window.open(href, "_blank");
    },
  },
};
</script>
<style lang="scss">
.vuepress-markdown-body h2 {
  font-size: 16px !important;
  font-weight: normal;
}
.vuepress-markdown-body {
  padding: 0 !important;
}
.container-xxl {
  padding-bottom: 100px;
}
.dotcontainer {
  display: inline-block;
  position: relative;
  margin-right: 3px;
  cursor: pointer;
  .dot {
    display: inline-block;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    width: 16px;
    height: 16px;
    background: #2794eb;
    color: #fff;
    font-size: 12px;
    line-height: 0;
  }
}
.dotcontainer:hover {
  .dotText {
    opacity: 1;
    visibility: visible;
  }
}

.dotText {
  position: absolute;
  transition: 0.5s;
  opacity: 0;
  visibility: hidden;
  top: 25px;
  left: 0;
  background: #2794eb;
  color: #fff;
  border-radius: 10px;
  padding: 10px;
  z-index: 2;
  width: 200px;
  font-size: 12px;
  a {
    color: #fff !important;
    font-size: 12px;
    text-decoration: none;
    word-wrap: break-word;
  }
}
.dotTextshow {
  display: block;
}
.linkboxTotal {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 10px;
  > div:last-child {
    margin-right: 0;
  }
}

.linkbox {
  position: relative;
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  background: #eeeeee;
  width: 25%;
  max-width: 150px;
  margin-right: 10px;
  font-size: 12px;
  padding: 8px;
  border-radius: 5px;
  transition: all 0.5s;
  margin-bottom: 10px;
  .dotcontainer {
    position: static;
  }
  .linktitle {
    color: #3b3b3b;
    text-overflow: ellipsis;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    width: 100%;
    margin-bottom: 10px;
    cursor: pointer;
  }
  .dotText {
    left: 50%;
    margin-left: -100px;
    top: 80px;
  }
  &:hover {
    background: #dfdfdf;
    .dotText {
      opacity: 1;
      visibility: visible;
    }
  }

  .dotcontainer:hover {
    .dotText {
      opacity: 0;
      visibility: hidden;
    }
  }
}

.hidelinkbox {
  display: none;
}

.linkurl {
  text-overflow: ellipsis;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  width: 100%;
}
.numlink {
  display: flex;
}
.related-question {
  margin: 10px 0 0 0 !important;
  padding-left: 0 !important;
  li {
    display: flex;
    justify-content: space-between;
    .question-content {
      display: flex;
      flex: 1;
    }
    .question-arrow {
      display: flex;
      width: 50px;
      align-items: center;
      color: #2794eb;
    }
  }
}
.vuepress-markdown-body a,
.vuepress-markdown-body p a code {
  color: #2794eb;
}
.vuepress-markdown-body ol,
.vuepress-markdown-body ul {
  margin: 0;
  padding-left: 0;
}

.model-title {
  display: block !important;
  font-size: 18px;
  color: #2794eb;
  font-weight: bold;
  margin-bottom: 10px !important;
  &::before {
    margin-right: 8px;
  }
}

.vuepress-markdown-body
  > div[data-v-md-line]:last-child
  > :last-child.model-title {
  margin-bottom: 10px !important;
}
.morerelation {
  cursor: pointer;
  color: #2794eb;
  margin-bottom: 20px;
}
</style>
<style scoped lang="scss">
.upload-icon-txt {
  display: flex;
  align-items: center;
  .el-icon-upload {
    margin-right: 10px;
  }
}
.btn-close-svg {
  cursor: pointer;
  top: -10px;
  right: -10px;
  position: absolute;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  border: 1px solid #bdbdbd;
  background: #fff;
  svg {
    width: 16px;
    height: 16px;
    margin: 0;
    padding: 0;
  }
}
.fileIcon {
  width: 20px;
  height: 20px;
  margin-right: 5px;
  background-size: 16px;
}

.attachment-file {
  display: flex;
  font-size: 12px;
  .attachment-file-item {
    position: relative;
    width: 150px;
    padding: 10px;
    border: 1px solid rgba(0, 0, 0, 0.08);
    border-radius: 5px;
    background: #fcfcfd;
    margin-right: 10px;
  }
  .attachment-name {
    width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    margin-bottom: 10px;
  }
}

.svg-icon {
  margin-right: 5px;
}
.message-fill {
  display: flex;
  justify-content: space-between;
}
.languagetype {
  margin-right: 20px;
}
.message-user-icon {
}
.message-user-ques {
  display: flex;
  padding: 10px 0 0 0;
  min-height: 40px;
}

.userprofile,
.message-reply-icon {
  display: flex;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  align-items: center;
  justify-content: center;
  .reply-icon {
    display: flex;
    width: 20px;
    height: 20px;
  }
}

.message-reply {
  display: flex;
}

.message-reply-cont {
  padding: 10px 0;
}

.message-reply-icon {
  background: #2794eb;
}
.message-user-icon {
  display: flex;
  margin-right: 20px;
}
.align-items-center {
  align-items: center !important;
}

.input-group {
  position: relative;
  display: flex;
  flex-wrap: wrap;
  align-items: stretch;
  width: 100%;
}
.el-icon-top {
  font-size: 24px;
}
.btn-submit-disable {
  width: 40px;
  height: 40px;
  border: 0;
  border-radius: 50% !important;
  background: #eee;
  .el-icon-top {
    color: #bdbdbd;
  }
}
.btn-submit-active {
  width: 40px;
  height: 40px;
  border: 0;
  border-radius: 50% !important;
  background: #2794eb;
  .el-icon-top {
    color: #fff;
  }
}
.form-control {
  position: relative;
  flex: 1 1 auto;
  width: 1%;
  min-width: 0;
}
.form-control {
  border-color: #f5f5f5;
  font-size: 14px;
  height: auto;
}

.border-0 {
  border: 0 !important;
}
.wave {
  position: relative;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  display: inline-flex;
  margin-left: 5px;
}
.wave .dot {
  display: inline-block;
  width: 3px;
  height: 3px;
  border-radius: 50%;
  margin-right: 5px;
  background: #2794eb;
  animation: wave 1.3s linear infinite;
}
.wave .dot:nth-child(2) {
  animation-delay: -1.1s;
}
.wave .dot:nth-child(3) {
  animation-delay: -0.9s;
}
@keyframes wave {
  0%,
  60%,
  100% {
    transform: initial;
  }
  30% {
    transform: translateY(-5px);
  }
}
.avatar.sm {
  height: 26px;
  width: 26px;
  font-size: 12px;
}
.rounded-circle {
  border-radius: 50% !important;
}
.message .avatar {
  border: 2px solid #2794eb;
}
.align-items-center {
  align-items: center !important;
}

.justify-content-end {
  justify-content: flex-end !important;
}
.chat-content .message .message-body {
  flex: 1;
}
.border,
.border-top,
.border-end,
.border-bottom,
.border-start {
  border-color: #f5f5f5 !important;
}
.border {
  border: 1px solid #f5f5f5 !important;
}
.p-3 {
  padding: 1rem !important;
}
.d-flex {
  display: flex !important;
}
.chat-content .message.right .message-content {
  background-color: transparent;
  text-align: left;
  border-radius: 15px 0 15px 15px;
}
.chat-content .message .message-content {
  border-radius: 0 15px 15px 15px;
  font-size: 16px;
}
.chat-content .message .message-send-title {
  display: flex;

  font-size: 18px;
  color: #3b3b3b;
  font-weight: bold;
}
.btn.btn-primary {
  background-color: #2794eb;
  border-color: #2794eb;
  width: 50px;
  height: 50px;
}
.chat-footer {
  position: fixed;
  display: flex;
  justify-content: center;
  width: 100%;
  bottom: 16px;
  margin: 0 auto;
  background: #fff;
}

.chat-footer-in {
  position: relative;
  width: 800px;
  min-width: 0px;
  outline: 2px solid transparent;
  outline-offset: 2px;
  -webkit-appearance: none;
  -moz-appearance: none;
  -ms-appearance: none;
  appearance: none;
  // transition-property: $chakra-transition-property-common;
  // transition-duration: $chakra-transition-duration-normal;
  font-weight: 500;
  border-radius: 30px;
  // font-size: $chakra-fontSizes-sm;
  // -webkit-padding-start: $chakra-space-4;
  // padding-inline-start: $chakra-space-4;
  // -webkit-padding-end: $chakra-space-4;
  // padding-inline-end: $chakra-space-4;
  border: 1px solid #d4d4d4;
  // border-color: $chakra-colors-gray-200;
  background: inherit;

  padding: 15px 20px;
  // color: $chakra-colors-navy-700;
  .chat-focus-list {
    display: flex;
  }

  .chat-focus {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60px;
    background: rgba(39, 148, 235, 0.1);
    padding: 5px;
    border-radius: 30px;
    color: #2794eb;
    margin-right: 10px;
 
  }

  .attachmentlist {
    display: flex;
    z-index: 1;
    position: absolute;
    background: #ffffff;
    color: #444444;
    width: 200px;
    height: 60px;
    align-items: center;
    padding: 20px;
    border-radius: 8px;
    border: 1px solid rgba(223, 223, 223, 0.5);
    background: rgba(255, 255, 255, 0.8);
    bottom: 50px;
    box-shadow: 0 1px 5px rgba(16, 24, 40, 0.1);
    .type-icon {
      display: flex;
    }
    .type-icon-active {
      color: #2794eb;
    }
    li {
      color: #676a6c;
      margin-right: 20px;
      cursor: pointer;
      .txt {
        margin-left: 10px;
      }
    }
  }
}
.home {
  position: relative;
  background-color: #fdfdfd;
  height: 100%;
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }
  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }
  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}
</style>

